package com.yupi.yuojcodesandbox.utils;

import cn.hutool.core.util.StrUtil;
import com.yupi.yuojcodesandbox.model.ExecuteMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ProcessUtils {
    /**
     * 执行进程并获取信息
     * @param runProcess
     * @param openName
     * @return
     */
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess,String openName){
        ExecuteMessage executeMessage = new ExecuteMessage();
        StopWatch stopWatch = new StopWatch();
        //开启计时
        stopWatch.start();
        try{
            //等待程序执行,获取错误码
            int exitValue = runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
            //正常退出
            if(exitValue==0){
                System.out.println(openName+"成功");
                //分批获取进程的正常输出流
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                List<String>outputStrList=new ArrayList<>();
                //逐行读取
                String compileOutputLine;
                while((compileOutputLine = bufferedReader.readLine())!=null){
                    outputStrList.add(compileOutputLine);
                }
                executeMessage.setMessage(StringUtils.join(outputStrList,"\n"));
            }else {
                //异常退出
                System.out.println(openName+"失败,错误码"+exitValue);
                //分批获取进程的错误输出
                BufferedReader errorbufferedReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                List<String>erroroutputStrList=new ArrayList<>();
                //逐行读取
                String errorcompileOutputLine;
                while((errorcompileOutputLine = errorbufferedReader.readLine())!=null){
                    erroroutputStrList.add(errorcompileOutputLine);
                }
                executeMessage.setErrorMessage(StringUtils.join(erroroutputStrList,"\n"));
//                System.out.println(errorstringBuilder);
            }


            stopWatch.stop();
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
        } catch (IOException | InterruptedException e ) {
            throw new RuntimeException(e);
        }

        return executeMessage;
    }

    /**
     * 执行交互式进程并获取信息
     * @param runProcess
     * @param
     * @return
     */
    public static ExecuteMessage runInterProcessAndGetMessage(Process runProcess,String args){
        ExecuteMessage executeMessage = new ExecuteMessage();
        try{
            //向控制台输入程序
            OutputStream outputStream = runProcess.getOutputStream();

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            String[] s = args.split(" ");
            String join=StrUtil.join("\n", s ) + "\n";
            outputStreamWriter.write(join);
            //相当于回车,执行输入的发送
            outputStreamWriter.flush();
            //分批获取进程的正常输出流
            InputStream inputStream = runProcess.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            //逐行读取
            String compileOutputLine;
            while((compileOutputLine = bufferedReader.readLine())!=null){
                stringBuilder.append(compileOutputLine);
            }
            executeMessage.setMessage(stringBuilder.toString());
            //释放资源
            inputStream.close();
            outputStream.close();
            outputStreamWriter.close();
            runProcess.destroy();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  executeMessage;
    }
}
